<template>
    <div class="home" @keydown.native="autoFocusOrder">
        <a-row :gutter="24">
            <a-col :span="12">
                <a-input-search
                    :value="orderSearchValue"
                    ref="orderSearcher"
                    placeholder="搜索订单号"
                    @change="onOrderSearcherChange"
                    @search="onOrderSearch"
                    @blur="onOrderSearchBlur"
                    enterButton
                ></a-input-search>
            </a-col>
            <a-col :span="12">
                <a-auto-complete placeholder="请输入购买者姓名或者联系电话" style="width: 100%" @select="onUserSelectorSelect" @search="onUserSelectorSearch">
                    <template slot="dataSource">
                        <a-select-option v-for="u in userSearchResult" :key="u.id">购买者：{{u.buyerName}}，电话：{{u.phone1}}</a-select-option>
                    </template>
                    <a-input @focus="onInputFocus" @blur="onInputBlur">
                        <a-icon slot="suffix" type="search" class="certain-category-icon"/>
                    </a-input>
                </a-auto-complete>
            </a-col>
        </a-row>
        <div class="card-group">
            <a-row :gutter="16">
                <a-col :span="6">
                    <a-card title="客户信息" :bodyStyle="{padding: '8px'}">
                        <div class="card-body card-body-center">
                            <h5>客户数量</h5>
                            <h1 style="margin:0px">{{users?users.length:''}}</h1>
                        </div>
                        <template class="ant-card-actions" slot="actions">
                            <a-icon type="user-add" @click="jumpTo('AddUser')"></a-icon>
                            <a-icon type="bars" @click="jumpTo('UserList')"/>
                        </template>
                    </a-card>
                </a-col>
                <a-col :span="6">
                    <a-card title="订单信息" :bodyStyle="{padding: '8px'}">
                        <div class="card-body card-body-left">
                            <div>订单数量：{{orders.length}}</div>
                            <div>订单金额：{{totalPrice}}元</div>
                            <div>到期订单：{{outdateOrders.length}}</div>
                            <div>完成订单：{{finishOrders.length}}</div>
                        </div>
                        <template class="ant-card-actions" slot="actions">
                            <a-icon type="file-add" @click="jumpTo('AddOrder')"/>
                            <a-icon type="bars" @click="jumpTo('OrderList')"/>
                        </template>
                    </a-card>
                </a-col>
                <a-col :span="6">
                    <a-card title="产品信息" :bodyStyle="{padding: '8px'}">
                        <div class="card-body card-body-center">
                            <h5>产品数量</h5>
                            <h1 style="margin:0px">{{products?products.length:''}}</h1>
                        </div>
                        <template class="ant-card-actions" slot="actions">
                            <a-icon type="setting" @click="jumpTo('AddProduct')"/>
                            <a-icon type="bars" @click="jumpTo('ProductList')"/>
                        </template>
                    </a-card>
                </a-col>
                <a-col :span="6">
                    <a-card title="数据库" :bodyStyle="{padding: '8px'}">
                        <div class="card-body card-body-center">
                            <h5>数据库版本</h5>
                            <h3 style="margin:0px">{{dbVersion}}</h3>
                        </div>
                        <template class="ant-card-actions" slot="actions" v-if="isAdmin">
                            <a-icon type="login" @click="jumpTo('ImportData')"/>
                            <a-icon type="logout" @click="jumpTo('ExportData')"/>
                            <a-icon type="edit" @click="onShowChangeAdminPassword()"/>
                        </template>
                        <template class="ant-card-actions" slot="actions" v-if="!isAdmin">
                            <a-icon type="dashboard" @click="loginToAdmin()"/>
                        </template>
                    </a-card>
                </a-col>
            </a-row>
        </div>
        <div class="table-group">
            <a-table bordered :columns="noticePresaleColumns" :dataSource="presaleNoticeList" rowKey="id">
                <template slot="title">即将到期的预售订单</template>
                <span slot="createDate" slot-scope="record">{{moment(record.createDate).format("YYYY-MM-DD HH:mm:ss")}}</span>
                <span slot="presaleOutdate" slot-scope="record">{{record.presaleOutdate?moment(record.presaleOutdate).format("YYYY-MM-DD HH:mm:ss"):''}}</span>
                <span slot="action" slot-scope="record">
                    <a @click="onItemDetail(record)">详情</a>
                </span>
            </a-table>
        </div>
        <div class="table-group">
            <a-table bordered :columns="noticeOrdersColumns" :dataSource="noticeOrders" rowKey="id">
                <template slot="title">即将到期的订单</template>
                <span slot="createDate" slot-scope="record">{{moment(record.createDate).format("YYYY-MM-DD HH:mm:ss")}}</span>
                <span slot="startDate" slot-scope="record">{{record.startDate?moment(record.startDate).format("YYYY-MM-DD HH:mm:ss"):''}}</span>
                <span slot="outDate" slot-scope="record">{{record.outDate?moment(record.outDate).format("YYYY-MM-DD HH:mm:ss"):''}}</span>
                <span slot="action" slot-scope="record">
                    <a @click="onItemDetail(record)">详情</a>
                </span>
            </a-table>
        </div>
        <div class="table-group">
            <a-table bordered :columns="outdateOrdersColumns" :dataSource="outdateOrders" rowKey="id">
                <template slot="title">已经到期的订单</template>
                <span slot="createDate" slot-scope="record">{{moment(record.createDate).format("YYYY-MM-DD HH:mm:ss")}}</span>
                <span slot="startDate" slot-scope="record">{{record.startDate?moment(record.startDate).format("YYYY-MM-DD HH:mm:ss"):''}}</span>
                <span slot="outDate" slot-scope="record">{{record.outDate?moment(record.outDate).format("YYYY-MM-DD HH:mm:ss"):''}}</span>
                <span slot="action" slot-scope="record">
                    <a @click="onItemDetail(record)">详情</a>
                </span>
            </a-table>
        </div>
        <a-modal title="请输入管理员密码" v-model="showAdminPasswordInputDialog" @ok="onAdminLogin">
            <a-input v-model="adminPassword" type="password"></a-input>
        </a-modal>
        <a-modal title="修改管理员密码" v-model="showAdminPasswordChangeDialog" @ok="onChangeAdminPassword">
            <a-input v-model="newAdminPassword" type="password" placeholder="请输入新密码"></a-input>
            <a-input style="margin-top:24px" v-model="reNewAdminPassword" type="password" placeholder="再次输入新密码"></a-input>
        </a-modal>
    </div>
</template>
<script>
import { mapGetters } from 'vuex';
import moment from 'moment';
moment.locale('zh-cn');
function formatNumber(value) {
    value += '';
    const list = value.split('.');
    const prefix = list[0].charAt(0) === '-' ? '-' : '';
    let num = prefix ? list[0].slice(1) : list[0];
    let result = '';
    while (num.length > 3) {
        result = `,${num.slice(-3)}${result}`;
        num = num.slice(0, num.length - 3);
    }
    if (num) {
        result = num + result;
    }
    return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
}
export default {
    name: 'Home',
    data() {
        return {
            orderSearchValue: '',
            userSearchResult: [],
            noticePresaleColumns: [
                {
                    title: '订单ID',
                    key: 'id',
                    dataIndex: 'id',
                    align: 'center'
                },
                {
                    title: '购买者姓名',
                    key: 'buyerName',
                    dataIndex: 'buyerName',
                    align: 'center'
                },
                {
                    title: '电话',
                    key: 'user.phone1',
                    dataIndex: 'user.phone1',
                    align: 'center'
                },
                {
                    title: '商品编号',
                    key: 'product.no',
                    dataIndex: 'product.no',
                    align: 'center'
                },
                {
                    title: '状态',
                    key: 'stateString',
                    dataIndex: 'stateString',
                    align: 'center'
                },
                {
                    title: '创建时间',
                    key: 'createDate',
                    scopedSlots: { customRender: 'createDate' },
                    align: 'center'
                },
                {
                    title: '预售到期时间',
                    key: 'presaleOutdate',
                    scopedSlots: { customRender: 'presaleOutdate' },
                    align: 'center'
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    scopedSlots: { customRender: 'action' }
                }
            ],
            noticeOrdersColumns: [
                {
                    title: '订单ID',
                    key: 'id',
                    dataIndex: 'id',
                    align: 'center'
                },
                {
                    title: '购买者姓名',
                    key: 'buyerName',
                    dataIndex: 'buyerName',
                    align: 'center'
                },
                {
                    title: '电话',
                    key: 'user.phone1',
                    dataIndex: 'user.phone1',
                    align: 'center'
                },
                {
                    title: '商品编号',
                    key: 'product.no',
                    dataIndex: 'product.no',
                    align: 'center'
                },
                {
                    title: '状态',
                    key: 'stateString',
                    dataIndex: 'stateString',
                    align: 'center'
                },
                {
                    title: '开始时间',
                    key: 'startDate',
                    scopedSlots: { customRender: 'startDate' },
                    align: 'center'
                },
                {
                    title: '到期时间',
                    key: 'outDate',
                    scopedSlots: { customRender: 'outDate' },
                    align: 'center'
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    scopedSlots: { customRender: 'action' }
                }
            ],
            outdateOrdersColumns: [
                {
                    title: '订单ID',
                    key: 'id',
                    dataIndex: 'id',
                    align: 'center'
                },
                {
                    title: '购买者姓名',
                    key: 'buyerName',
                    dataIndex: 'buyerName',
                    align: 'center'
                },
                {
                    title: '电话',
                    key: 'user.phone1',
                    dataIndex: 'user.phone1',
                    align: 'center'
                },
                {
                    title: '商品编号',
                    key: 'product.no',
                    dataIndex: 'product.no',
                    align: 'center'
                },
                {
                    title: '状态',
                    key: 'stateString',
                    dataIndex: 'stateString',
                    align: 'center'
                },
                {
                    title: '开始时间',
                    key: 'startDate',
                    scopedSlots: { customRender: 'startDate' },
                    align: 'center'
                },
                {
                    title: '到期时间',
                    key: 'outDate',
                    scopedSlots: { customRender: 'outDate' },
                    align: 'center'
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    scopedSlots: { customRender: 'action' }
                }
            ],
            moment,
            showAdminPasswordInputDialog: false,
            showAdminPasswordChangeDialog: false,
            adminPassword: '',
            newAdminPassword: '',
            reNewAdminPassword: ''
        };
    },
    created() {
        window.addEventListener('keydown', this.autoFocusOrder);
    },
    methods: {
        formatNumber,
        jumpTo(routeName) {
            this.$router.push({
                name: routeName
            });
        },
        autoFocusOrder() {
            this.$refs.orderSearcher.focus();
        },
        onItemDetail(item) {
            this.$router.push({
                name: 'OrderDetail',
                query: {
                    id: item.id
                }
            });
        },
        onOrderSearcherChange(e) {
            const { value } = e.target;
            const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
            if (
                (!isNaN(value) && reg.test(value)) ||
                value === '' ||
                value === '-'
            ) {
                this.orderSearchValue = value;
            }
        },
        onOrderSearchBlur() {
            const { orderSearchValue, onOrderSearcherChange } = this;
            if (
                orderSearchValue.charAt(orderSearchValue.length - 1) === '.' ||
                orderSearchValue === '-'
            ) {
                onOrderSearcherChange({
                    orderSearchValue: orderSearchValue.slice(0, -1)
                });
            }
        },
        onOrderSearch() {
            if (this.orderSearchValue && this.orderSearchValue !== '') {
                this.$router.push({
                    name: 'OrderDetail',
                    query: {
                        id: this.orderSearchValue.toString()
                    }
                });
            }
        },
        onInputFocus() {
            window.removeEventListener('keydown', this.autoFocusOrder);
        },
        onInputBlur() {
            window.addEventListener('keydown', this.autoFocusOrder);
        },
        onUserSelectorSelect(value) {
            let user = _.find(this.users, { id: value });
            if (user) {
                this.$router.push({
                    name: 'UserDetail',
                    query: {
                        id: user.id
                    }
                });
            }
        },
        onUserSelectorSearch(value) {
            if (value === '') {
                return;
            }
            this.userSearchResult = _.filter(this.users, item => {
                return (
                    item.buyerName.includes(value) ||
                    item.phone1.includes(value)
                );
            });
        },
        loginToAdmin() {
            this.showAdminPasswordInputDialog = true;
            window.removeEventListener('keydown', this.autoFocusOrder);
        },
        onAdminLogin() {
            this.$store
                .dispatch('checkAdminPassword', this.adminPassword)
                .then(() => {
                    this.showAdminPasswordInputDialog = false;
                    this.$store.commit('setAdmin', true);
                    window.addEventListener('keydown', this.autoFocusOrder);
                    this.adminPassword = '';
                })
                .catch(reason => {
                    this.$error({ title: reason.message });
                });
        },
        onShowChangeAdminPassword() {
            this.showAdminPasswordChangeDialog = true;
            window.removeEventListener('keydown', this.autoFocusOrder);
        },
        onChangeAdminPassword() {
            if (this.newAdminPassword !== this.reNewAdminPassword) {
                this.$error({ title: '两次输入的密码不一致' });
                return;
            }
            if (this.newAdminPassword === '') {
                this.$error({ title: '密码不能为空' });
                return;
            }
            this.$store
                .dispatch('changeAdminPassword', this.newAdminPassword)
                .then(() => {
                    this.showAdminPasswordChangeDialog = false;
                    window.addEventListener('keydown', this.autoFocusOrder);
                    this.$success({ title: '密码修改成功' });
                    this.newAdminPassword = '';
                    this.reNewAdminPassword = '';
                })
                .catch(reason => {
                    this.$error({ title: reason.message });
                });
        }
    },
    computed: {
        ...mapGetters([
            'outdateOrders',
            'finishOrders',
            'noticeOrders',
            'users',
            'orders',
            'products',
            'totalPrice',
            'dbVersion',
            'isAdmin',
            'presaleNoticeList'
        ])
    },
    beforeDestroy() {
        window.removeEventListener('keydown', this.autoFocusOrder);
    }
};
</script>

<style scoped lang="stylus">
.home {
    display: flex;
    flex-direction: column;

    .searchArea {
        display: flex;
    }

    .card-group {
        margin-top: 24px;

        .card-body {
            width: 100%;
            height: 100px;
            display: flex;
            flex-direction: column;
        }

        .card-body-center {
            justify-content: center;
            align-items: center;
        }

        .card-body-left {
            justify-content: center;
            align-items: start;
        }
    }

    .table-group {
        margin-top: 24px;
    }
}
</style>
